package qs.openxt.libs.progress;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.AnimationDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import qs.openxt.libs.R;
import qs.openxt.libs.util.MResource;
import qs.openxt.libs.util.StringUtil;

public class Wait {
	private static Wait _sharedInstance = null;
	private Dialog dialog = null;

	private static int showCount = 0;

	public static Wait sharedInstance(){
		if(_sharedInstance == null)
			_sharedInstance = new Wait();

		return _sharedInstance;
	}

	public void start(Context context, String msg){
		if(dialog != null){
			showCount++;

			TextView tv = (TextView)dialog.findViewById(R.id.dialog_iv_loading_label);
			if(!StringUtil.isNull(msg))
				tv.setText(msg);
			return;
		}
		showCount++;
		dialog = new Dialog(context, R.style.custom_progress_dialog);
		View actionView = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
		TextView tv = (TextView)actionView.findViewById(R.id.dialog_iv_loading_label);
		if(!StringUtil.isNull(msg))
			tv.setText(msg);
		ImageView loadingImage = (ImageView) actionView.findViewById(R.id.dialog_iv_loading);
		if (loadingImage.getBackground() instanceof AnimationDrawable) {
			AnimationDrawable animationDrawable = (AnimationDrawable) loadingImage.getBackground();
			animationDrawable.start();
		}
		dialog.setContentView(actionView);
		dialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				stop();
			}
		});
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(true);
		dialog.show();
	}

	public void stop(){
		if(dialog == null){
			showCount = 0;
			return;
		}
		showCount--;
		if(showCount <= 0){
			showCount = 0;
			try {
				dialog.dismiss();
				dialog = null;
			} catch (Exception e) {
				dialog = null;
			}
		}
	}

	public void stopAll(){
		if(dialog == null){
			showCount = 0;
			return;
		}
		showCount = 0;
		try {
			dialog.dismiss();
			dialog = null;
		} catch (Exception e) {
			dialog = null;
		}
	}
}
